import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * 功能: 注册功能
 * 目标:在用户表userinfo中插入1条表记录
 * INSERT INTO userinfo(id,username,password,nickname,age) VALUES(NULL,'Tony','123456','tony',18)
 */
public class JDBCDemo1 {
    public static void main(String[] args) {
        /*
            1.加载数据库驱动:Class.forName("");
            2.创建数据库连接对象:DriverManager.getConnection();
            3.创建SQL语句执行对象:connection.createStatement();
            4.执行SQL语句[增删改查]:statement.executeUpdate("");
            5.断开数据库连接:connection.close();
         */
        try {
            //1.加载数据库驱动[try-catch]
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.创建数据库连接对象[使用DriverManager.getConnection()]
            // getConnection().var+回车+回车
            Connection connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                    "root",
                    "root"
            );
            //3.创建执行对象: .var+回车+回车
            Statement statement = connection.createStatement();
            //4.执行SQL语句
            //  executeUpdate(): 执行增删改语句
            /*
                请输入用户名:
                请输入密码:
                请输入昵称:
                请输入年龄:
             */
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名:");
            String username = scanner.nextLine();
            System.out.println("请输入密码:");
            String password = scanner.nextLine();
            System.out.println("请输入昵称:");
            String nickname = scanner.nextLine();
            System.out.println("请输入年龄:");
            int age = scanner.nextInt();

            //字符串拼接SQL: "+变量名+"
            String sql = "INSERT INTO userinfo(id,username,password,nickname,age) VALUES(NULL,'"+username+"','"+password+"','"+nickname+"',"+age+")";
            int i = statement.executeUpdate(sql);
            //5.断开数据库连接
            connection.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}















